package com.xiaomo.gitee.datamanager.security.handler;

import com.xiaomo.gitee.datamanager.aspect.log.anno.SysLog;
import com.xiaomo.gitee.datamanager.mapper.UserMapper;
import com.xiaomo.gitee.datamanager.util.JwtUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NoArgsConstructor;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@NoArgsConstructor
@Lazy(false)
public class LogoutSuccessHandler implements org.springframework.security.web.authentication.logout.LogoutSuccessHandler {

    private JwtUtils jwtUtils;
    private UserMapper userMapper;

    @Autowired
    public LogoutSuccessHandler(JwtUtils jwtUtils, UserMapper userMapper) {
        this.jwtUtils = jwtUtils;
        this.userMapper = userMapper;
    }

    @Override
    @SysLog("用户登出")
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if (authentication != null) {
            new SecurityContextLogoutHandler().logout(request,response,authentication);
        }
        //response.setHeader(JwtUtils.HTTP_HEADER,"");
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if (cookie.getName().equals(JwtUtils.TOKEN_HEADER)) {
                    String name = userMapper.selectOneById(Long.parseLong(jwtUtils.getPayloadArguments(cookie.getValue()).getStr("userId"))).getUsername();
                    MDC.put("退出用户",name);
                    break;
                }
            }
        }
        Cookie cookie = new Cookie(JwtUtils.TOKEN_HEADER,null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        response.sendRedirect("/login");

    }
}
